const DepartmentModel = require('../models/departmentModel');
const { getLogger } = require('../logger');
const logger = getLogger('controllers.departmentController');
const { success, error, serverError, notFound, badRequest } = require('../utils/response');
const { logAudit } = require('../utils/auditLogger');
const { validateRequired, validateId } = require('../utils/validator');

// 获取所有部门
const getAllDepartments = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
    
        // 构建过滤条件
        const filters = {};
        if (req.query.name) filters.name = req.query.name;
        if (req.query.code) filters.code = req.query.code;
        if (req.query.type !== undefined) filters.type = parseInt(req.query.type);
        if (req.query.parent_id !== undefined) filters.parent_id = parseInt(req.query.parent_id);

        const [departments, total] = await Promise.all([
            DepartmentModel.getAllDepartments(page, limit, filters),
            DepartmentModel.getDepartmentCount(filters)
        ]);

        await logAudit(req, { action_type: 'view', module_code: 'department', business_type: 'list', operation_desc: 'list' });
        success(req, res, '获取部门列表成功', {
            data:departments,
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        });
    } catch (err) {
        logger.error('获取部门列表错误', { error: err });
        serverError(req, res, '获取部门列表失败');
    }
};

// 获取部门树结构
const getDepartmentTree = async (req, res) => {
    try {
        const tree = await DepartmentModel.getDepartmentTree();
        await logAudit(req, { action_type: 'view', module_code: 'department', business_type: 'tree', operation_desc: 'tree' });
        success(req, res, '获取部门树结构成功', tree);
    } catch (err) {
        logger.error('获取部门树结构错误', { error: err });
        serverError(req, res, '获取部门树结构失败');
    }
};

// 获取部门详情
const getDepartment = async (req, res) => {
    const { id } = req.params;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '部门ID格式错误');
        }

        const department = await DepartmentModel.findById(id);
        if (!department) {
            return notFound(req, res, '部门不存在');
        }

        await logAudit(req, { action_type: 'view', module_code: 'department', business_type: 'detail', operation_desc: 'detail', target_entity_type: 'department', target_entity_id: id });
        success(req, res, '获取部门信息成功', department);
    } catch (err) {
        logger.error('获取部门信息错误', { error: err });
        serverError(req, res, '获取部门信息失败');
    }
};

// 创建部门
const createDepartment = async (req, res) => {
    const { name, type, code, parent_id ,manager_id,phone,email,address,short_name,responsibility,description} = req.body;
    
    try {
        // 从认证中间件获取当前用户ID
        const currentUserId = req.user?.id;
        
        // 输入验证
        const requiredValidation = validateRequired(req.body, ['name','parent_id','short_name']);
        if (!requiredValidation.isValid) {
            return badRequest(req, res, requiredValidation.message);
        }

        // 验证类型 - 确保type是有效的数字类型
        const typeNum = parseInt(type);
        if (isNaN(typeNum) || ![0, 1].includes(typeNum)) {
            return badRequest(req, res, '部门类型只能是0(组织)或1(部门)');
        }

        // 如果提供了父级ID，验证父级部门是否存在
        if (parent_id) {
            if (!validateId(parent_id)) {
                return badRequest(req, res, '父级部门ID格式错误');
            }
            
            const parentDept = await DepartmentModel.findById(parent_id);
            if (!parentDept) {
                return badRequest(req, res, '父级部门不存在');
            }
        }

        // 如果提供了编码，检查是否重复
        if (code) {
            const codeExists = await DepartmentModel.isCodeExists(code);
            if (codeExists) {
                return badRequest(req, res, '部门编码已存在');
            }
        }

        // 创建部门 - 使用验证过的typeNum变量
        const params = {
            name,
            type: typeNum,
            code,
            parent_id: parent_id ? parseInt(parent_id) : null,
            manager_id,
            phone,
            email,
            address,
            description,
            short_name,
            responsibility,
            create_by: currentUserId
        };
        
        const departmentId = await DepartmentModel.create(params,currentUserId);
        await logAudit(req, { action_type: 'create', module_code: 'department', business_type: 'department', operation_desc: 'create', target_entity_type: 'department', target_entity_id: departmentId, target_entity_name: name, after_data: params });
        success(req, res, '部门创建成功', {
            id: departmentId,
            ...params
        });
    } catch (err) {
        logger.error('创建部门错误', { error: err });
        serverError(req, res, '创建部门失败');
    }
};

// 更新部门
const updateDepartment = async (req, res) => {
    const { id,name, type, code, parent_id ,manager_id,phone,email,address,short_name,responsibility } = req.body;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '部门ID格式错误');
        }

        const currentUserId = req.user?.id;

        // 检查部门是否存在
        const existingDept = await DepartmentModel.findById(id);
        if (!existingDept) {
            return notFound(req, res, '部门不存在');
        }

        // 验证类型
        if (type !== undefined && ![0, 1].includes(parseInt(type))) {
            return badRequest(req, res, '部门类型只能是0(组织)或1(部门)');
        }

        // 如果提供了父级ID，验证父级部门是否存在且不能是自己
        if (parent_id !== undefined) {
            if (parent_id && !validateId(parent_id)) {
                return badRequest(req, res, '父级部门ID格式错误');
            }
            
            if (parent_id && parseInt(parent_id) === parseInt(id)) {
                return badRequest(req, res, '不能将自己设为父级部门');
            }
            
            if (parent_id) {
                const parentDept = await DepartmentModel.findById(parent_id);
                if (!parentDept) {
                    return badRequest(req, res, '父级部门不存在');
                }
                
                // 检查是否会形成循环引用
                const allChildren = await DepartmentModel.getAllChildren(id);
                const childIds = allChildren.map(child => child.id);
                if (childIds.includes(parseInt(parent_id))) {
                    return badRequest(req, res, '不能将子部门设为父级部门');
                }
            }
        }

        // 如果提供了新的编码，检查是否重复
        if (code && code !== existingDept.code) {
            const codeExists = await DepartmentModel.isCodeExists(code, id);
            if (codeExists) {
                return badRequest(req, res, '部门编码已存在');
            }
        }

        // 更新部门信息
        const params = {
            name: name || existingDept.name,
            type: type !== undefined ? parseInt(type) : existingDept.type,
            code: code || existingDept.code,
            parent_id: parent_id !== undefined ? (parent_id ? parseInt(parent_id) : null) : existingDept.parent_id,
            manager_id,
            phone,
            email,
            address,
            // description,
            short_name,
            responsibility,
            update_by: currentUserId
        };

        const affectedRows = await DepartmentModel.update(id, params,currentUserId);
        
        if (affectedRows > 0) {
            const updatedDept = await DepartmentModel.findById(id);
            await logAudit(req, { action_type: 'update', module_code: 'department', business_type: 'department', operation_desc: 'update', target_entity_type: 'department', target_entity_id: id, target_entity_name: updatedDept.name, before_data: existingDept, after_data: updatedDept });
            success(req, res, '部门更新成功', updatedDept);
        } else {
            serverError(req, res, '部门更新失败');
        }
    } catch (err) {
        logger.error('更新部门错误', { error: err });
        serverError(req, res, '更新部门失败');
    }
};

// 删除部门
const removeDepartment = async (req, res) => {
    const { id } = req.params;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '部门ID格式错误');
        }

        // 检查部门是否存在
        const existingDept = await DepartmentModel.findById(id);
        if (!existingDept) {
            return notFound(req, res, '部门不存在');
        }

        // 检查部门是否可以删除
        const deletable = await DepartmentModel.isDeletable(id);
        if (!deletable) {
            return badRequest(req, res, '该部门下还有子部门或用户，无法删除');
        }

        // 检查部门是否绑定有用户
        const isbinduser = await DepartmentModel.isBindUser(id);
        if (isbinduser) {
            return badRequest(req, res, '该部门绑定有用户，无法删除');
        }

        // 删除部门
        const affectedRows = await DepartmentModel.deleteById(id);
        
        if (affectedRows > 0) {
            await logAudit(req, { action_type: 'delete', module_code: 'department', business_type: 'department', operation_desc: 'delete', target_entity_type: 'department', target_entity_id: id, target_entity_name: existingDept.name, before_data: existingDept });
            success(req, res, '部门删除成功');
        } else {
            serverError(req, res, '部门删除失败');
        }
    } catch (err) {
        logger.error('删除部门错误', { error: err });
        serverError(req, res, '删除部门失败');
    }
};

// 获取子部门
const getChildrenDepartments = async (req, res) => {
    const { id } = req.params;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '部门ID格式错误');
        }

        const children = await DepartmentModel.findByParentId(id);
        await logAudit(req, { action_type: 'view', module_code: 'department', business_type: 'children', operation_desc: 'list', target_entity_type: 'department', target_entity_id: id });
        success(req, res, '获取子部门成功', children);
    } catch (err) {
        logger.error('获取子部门错误', { error: err });
        serverError(req, res, '获取子部门失败');
    }
};

// 获取所有子部门（包括子子部门）
const getAllChildrenDepartments = async (req, res) => {
    const { id } = req.params;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '部门ID格式错误');
        }

        const children = await DepartmentModel.getAllChildren(id);
        await logAudit(req, { action_type: 'view', module_code: 'department', business_type: 'children_all', operation_desc: 'list', target_entity_type: 'department', target_entity_id: id });
        success(req, res, '获取所有子部门成功', children);
    } catch (err) {
        logger.error('获取所有子部门错误', { error: err });
        serverError(req, res, '获取所有子部门失败');
    }
};

// 获取父部门
const getParentDepartments = async (req, res) => {
    const { id } = req.params;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '部门ID格式错误');
        }

        const parents = await DepartmentModel.getAllParents(id);
        await logAudit(req, { action_type: 'view', module_code: 'department', business_type: 'parents', operation_desc: 'list', target_entity_type: 'department', target_entity_id: id });
        success(req, res, '获取父部门成功', parents);
    } catch (err) {
        logger.error('获取父部门错误', { error: err });
        serverError(req, res, '获取父部门失败');
    }
};

// 获取部门统计信息
const getDepartmentStats = async (req, res) => {
    try {
        const stats = await DepartmentModel.getDepartmentStats();
        await logAudit(req, { action_type: 'view', module_code: 'department', business_type: 'stats', operation_desc: 'stats' });
        success(req, res, '获取部门统计信息成功', stats);
    } catch (err) {
        logger.error('获取部门统计信息错误', { error: err });
        serverError(req, res, '获取部门统计信息失败');
    }
};

// 获取部门用户数量
const getDepartmentUserCount = async (req, res) => {
    const { id } = req.params;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '部门ID格式错误');
        }

        const userCount = await DepartmentModel.getUserCount(id);
        await logAudit(req, { action_type: 'view', module_code: 'department', business_type: 'user_count', operation_desc: 'count', target_entity_type: 'department', target_entity_id: id });
        success(req, res, '获取部门用户数量成功', { userCount });
    } catch (err) {
        logger.error('获取部门用户数量错误', { error: err });
        serverError(req, res, '获取部门用户数量失败');
    }
};

// 检查部门是否可以删除
const checkDepartmentDeletable = async (req, res) => {
    const { id } = req.params;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '部门ID格式错误');
        }

        const deletable = await DepartmentModel.isDeletable(id);
        
        await logAudit(req, { action_type: 'view', module_code: 'department', business_type: 'deletable', operation_desc: 'check', target_entity_type: 'department', target_entity_id: id });
        success(req, res, '检查部门删除状态成功', {
            deletable,
            message: deletable ? '可以删除' : '不能删除，该部门下有子部门或用户'
        });
    } catch (err) {
        logger.error('检查部门删除状态错误', { error: err });
        serverError(req, res, '检查部门删除状态失败');
    }
};

// 获取可选的部门负责人列表
const getManagerList = async (req, res) => {
    try {
        // 从查询参数中获取部门ID，如果不存在则为null
        const { department_id } = req.query;
        // 转换部门ID为数字类型（如果提供了）
        const departmentId = department_id ? Number(department_id) : null;
        
        // 调用模型方法获取负责人列表
        const managers = await DepartmentModel.getManagerList(departmentId);
        success(req, res, '获取部门负责人列表成功', managers);
    } catch (err) {
        logger.error('获取部门负责人列表错误', { error: err });
        serverError(req, res, '获取部门负责人列表失败');
    }
};

module.exports = {
    getAllDepartments,
    getDepartmentTree,
    getDepartment,
    createDepartment,
    updateDepartment,
    removeDepartment,
    getChildrenDepartments,
    getAllChildrenDepartments,
    getParentDepartments,
    getDepartmentStats,
    getDepartmentUserCount,
    checkDepartmentDeletable,
    getManagerList
};
